/**
 * Muis
 *
 * Deze klasse houd de verplaatsing van 1 muis bij, tot deze wordt gereset*
 *
 * @author Youri Hemeleers <Youri.Hemeleers@Gmail.Com>
 * @date    24/02/11
 * @modified Jasper Nevens <jasper.nevens@gmail.com>
 * @date	24/03/11
 */

#include "muis.h"

#define LBZ  -256 //low byte zero (2's comp)
#define XNEG 0x10
#define YNEG 0x20

using namespace std;


Muis::Muis(string dev)
{
	cout << "Mouse "<< dev <<" initialize..." << endl;
	device=dev;
	verbose = false;
	devFile.open( dev.c_str() , ios::in | ios::binary);
	if( ! devFile.is_open() )
	{
		cout << "file not open !!" << endl;
	}
	setDPI(300);
	setAngle(0.0);
}

Muis:: ~Muis(void)
{
	devFile.close();		 
	cout << "Mouse destructed..." << endl;	
}

// debug
void Muis::reset(void){
	x=0;
	y=0;
	angle=0;
}

void Muis::setVerbose(bool v)
{
	verbose = v;
}

// set correction factors
void Muis::setAngle(float a)
{
	angle=a;
}
void Muis::setDPI(int d)
{
	dpi=d;
}

// set position
void Muis::setX(int xi)
{
	x=xi*dpi/25.4;
}
void Muis::setY(int yi)
{
	y=yi*dpi/25.4;
}

// retrieve position
int Muis::getX(void)
{
	// return corrected distance
	return x*25.4/dpi;
}
int	Muis::getY(void)
{
	// return corrected distance
	return y*25.4/dpi;
}

// other
void Muis::execute()
{
	char b[3];
	int xm,ym,xc,yc;
	float a,h,hn;
	while(! devFile.eof() && devFile.is_open())
	{
		devFile.read (b , 3);
		//3 bytes gelezen , zet int op negatief (lower 8 bit 0 laten)
		(XNEG & b[0])? xm=LBZ : xm=0;
		(YNEG & b[0])? ym=LBZ : ym=0;
		//de waarde geOR'd op de sign-extended int
		ym |= b[2] ;
		xm |= b[1] ;
		// correction angle
		if(xm==0)
			h=(ym > 0) ? M_PI/2 : -M_PI/2;
		else
			h=atan((float)ym/(float)xm);
		if(xm < 0) h += M_PI;
		a=sqrt(xm*xm+ym*ym);
		
		cout << a << "," << h << endl;
		
		hn=h-angle;
		xc=a*cos(hn);
		yc=a*sin(hn);
		//houd bij hoeveel er bewogen is
		x+=(int)xc;
		y+=(int)yc;
		
		// debug	
		if(verbose)
		{
			cout << device << " : " << endl;
			cout << "data :" << xm << " , " << ym << endl;
			cout << "verpl: x:"<< x <<"dots, y:"<< y << "dots" << endl;
			cout << "verpl: x:"<< getX() <<"mm, y:"<< getY() << "mm" << endl;
		}
	}
	cout << "out of execution loop -> not reading data !" << endl ;
}


